package com.web.atmt.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.web.atmt.bean.Attachment;
import com.web.atmt.service.AttachmentService;
import com.web.atmt.service.impl.AttachmentServiceImpl;

@SuppressWarnings("serial")
public class AttachmentAction extends ActionSupport {

	private File file;

	private String param;
	
	private static String fileRoot = null;
	
	private String fileName;

	private Map<String, Object> result;

	private AttachmentService service;

	public AttachmentAction() {
		this.result = new HashMap<String, Object>();
		this.service = new AttachmentServiceImpl();
		if (fileRoot == null) {
			Properties prop = new Properties();
			try {
		        prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("file_upload.properties"));
		        fileRoot = prop.getProperty("file.root");
	        } catch (IOException e) {
		        e.printStackTrace();
	        }
		}
	}
	
	public String load() {
		this.result.put("success", true);
		HttpServletRequest request = ServletActionContext.getRequest();
		
		try {
			String otherId = request.getParameter("otherId");
			String typeId = request.getParameter("typeId");
			
	        List<Attachment> list = this.service.loadAttachment(otherId, typeId);
	        this.result.put("files", list);
        } catch (Exception e) {
    		this.result.put("success", false);
	        e.printStackTrace();
        }
		
		return SUCCESS;
	}

	public String upload() {
		this.result.put("success", true);
		HttpServletRequest request = ServletActionContext.getRequest();
		
		try {
			JSONObject fileParam = JSONObject.fromObject(this.param);
			String fileId = String.valueOf(System.currentTimeMillis());
			this.result.put("id", fileId);
			String saveName = UUID.randomUUID() + fileParam.getString("type");
			String otherId = request.getParameter("otherId");
			String typeId = request.getParameter("typeId");

			String path = fileRoot + this.service.getUploadPath(typeId);
			FileUtils.moveFile(this.file, new File(path + saveName));

			this.service.addAttachment(fileId, fileParam.getString("name"), fileParam.getString("type"),
			        fileParam.getInt("size"), saveName, otherId, typeId);
		} catch (Exception e) {
			this.result.put("success", false);
			e.printStackTrace();
		}

		return SUCCESS;
	}
	
	public String remove() {
		this.result.put("success", true);
		HttpServletRequest request = ServletActionContext.getRequest();
		
		try {
			String fileIds = request.getParameter("id");
			JSONArray ja = JSONArray.fromObject(fileIds);
			fileIds = StringUtils.join(ja.toArray(), ",");
			List<Attachment> list = this.service.getRemoveFile(fileIds);
			
			if (list != null && list.size() > 0) {
				for (Attachment record : list) {
					FileUtils.deleteQuietly(new File(fileRoot + record.getPath()));
				}
			}
			this.service.removeAttachment(fileIds);
		} catch (Exception e) {
			this.result.put("success", false);
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	public InputStream getInputStream() throws SQLException, IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String fileId = request.getParameter("id");
		
		Attachment attach = this.service.getDownloadFile(fileId);
		if (attach != null) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(attach.getName(), "UTF-8"));
			this.setFileName(attach.getName());
			return new FileInputStream(new File(fileRoot + attach.getPath()));
		}
		
		return null;
	}
	
	public String download() {
		return SUCCESS;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) throws UnsupportedEncodingException {
		this.fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
	}

	public Map<String, Object> getResult() {
		return result;
	}

	public void setResult(Map<String, Object> result) {
		this.result = result;
	}

	public AttachmentService getService() {
		return service;
	}

	public void setService(AttachmentService service) {
		this.service = service;
	}

}
